<?php

namespace app\controller;

use app\BaseController;
use Shiwei\Tools\Format;
use think\facade\Db;

/**
 * 默认控制器
 * Class Index
 * @package app\api\controller
 */
class Index extends BaseController
{
    public function index()
    {
        echo '当前访问的index.php，请将index.html设为默认站点入口';
    }

    public function register()
    {
        $invite_list = [
            'a11',
            'a22',
            'a33',
            'a44',
            'a55',
            'a66',
            'a77',
            'a88',
            'a99',
        ];
        
        $formData = request()->param('form', []);

        if (!isset($formData['username']) || empty($formData['username'])) {
            return json(['code' => 1001, 'msg' => '请输入用户名']);
        }

        if (!preg_match('/^[a-zA-Z0-9_]+$/', $formData['username'])) {
            return json(['code' => 1001, 'msg' => '用户名格式错误']);
        }

        if (Db::name('register')->where(['username' => $formData['username']])->count()) {
            return json(['code' => 1001, 'msg' => '用户名已存在']);
        }

        if (!isset($formData['password']) || empty($formData['password'])) {
            return json(['code' => 1001, 'msg' => '请输入密码']);
        }

        if (!isset($formData['invite_code']) || empty($formData['invite_code'])) {
            return json(['code' => 1001, 'msg' => '请输入邀请码']);
        }

        if (!in_array($formData['invite_code'], $invite_list)) {
            return json(['code' => 1001, 'msg' => '邀请码错误']);
        }

        $formData['create_time'] = time();
        $formData['update_time'] = time();

        if (!Db::name('register')->insert($formData)) {
            return json(['code' => 1001, 'msg' => '注册失败']);
        }

        return json(['code' => 1000, 'msg' => '注册成功']);
    }

    public function list()
    {
        $limit    = request()->param('limit', 15);
        $formData = request()->param('form', []);

        $filters = [];

        if (isset($formData['invite_code']) && !empty($formData['invite_code'])) {
            $filters[] = ['invite_code', '=', $formData['invite_code']];
        }

        $list  = Db::name('register')->where($filters)->order(['create_time' => 'desc'])->paginate($limit)->toArray();
        
        foreach ($list['data'] as &$row) {
            $row['create_time'] = Format::timeToString($row['create_time']);
            $row['update_time'] = Format::timeToString($row['update_time']);
        }

        return json(['code' => 1000, 'msg' => '成功', 'data' => $list]);
    }
}